package testredis;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.Response;
import redis.clients.jedis.Transaction;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TestRedis {

    public static void main(String[] args)  {
        new TestRedis().test();

    }

    public void test(){
        ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
        for (int i = 0; i < 10; i++) {
            cachedThreadPool.execute(new TestRunnable(i));
        }
        cachedThreadPool.shutdown();
    }


    public  class TestRunnable implements Runnable{

        int i;

        public TestRunnable(int i){
            this.i=i;
        }

        @Override
        public void run() {
            Thread.currentThread().setName("tr-"+i);

            Jedis jedis = new Jedis("localhost");

            while (true){
                jedis.watch("jishu");
                Transaction multi = jedis.multi();
                Response<String> beforejishu = multi.get("jishu");
                multi.incrBy("jishu",i);
                Response<String> afterjishu = multi.get("jishu");
                List<Object> exec = multi.exec();
                if(exec.size()>0){
                    System.out.println(Thread.currentThread().toString()+".exec."+exec);
                    System.out.println(Thread.currentThread().toString()+beforejishu.get());
                    System.out.println(Thread.currentThread().toString()+afterjishu.get());
                    break;
                }
            }
        }
    }

}


